package com.ddc.study.feature.html;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.ddc.study.R;
import com.ddc.study.base.MvpActivity;
import com.ddc.study.net.NetworkUtil;
import com.ddc.study.util.Log;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.net.URISyntaxException;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import butterknife.BindView;

/**
 * Created on 2018/4/19.
 *
 * @author lshun
 * @version 1.0
 */
public class HtmlActivity extends MvpActivity<HtmlContract.IView, HtmlContract.IPresenter>
        implements HtmlContract.IView {
    private static final String INTENT_URL = "url";

    @BindView(R.id.loading_progress)
    ProgressBar mProgressBar;

    @BindView(R.id.web_view)
    WebView mWebView;

    @Override
    protected HtmlContract.IPresenter createPresenter() {
        return new HtmlPresenter();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_html;
    }

    public static void openUrl(@NonNull Context context, String url) {
        Intent intent = new Intent(context, HtmlActivity.class);
        intent.putExtra(INTENT_URL, url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //声明WebSettings子类
        WebSettings webSettings = mWebView.getSettings();

        //如果访问的页面中要与Javascript交互，则web view必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //支持插件
//        webSettings.setPluginsEnabled(true);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合web view的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        // 缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        // 其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭web view中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("UTF-8");//设置编码格式
        webSettings.setBlockNetworkImage(false);//解决图片不显示

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //设置支持HTTP与HTTPS混合模式
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e(TAG, "shouldOverrideUrlLoading -> " + url);

                //TODO 根据规则拦截
                if (url.startsWith("intent:")) {
                    try {
                        final Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        intent.addCategory(Intent.CATEGORY_BROWSABLE);

                        List<ResolveInfo> infoList = getPackageManager()
                                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                        if (infoList == null || infoList.isEmpty()) {
                            showToast("没有选择");
                        } else if (infoList.size() == 1) {
                            String name = infoList.get(0).activityInfo.applicationInfo.
                                    loadLabel(getPackageManager()).toString();
                            new AlertDialog.Builder(HtmlActivity.this)
                                    .setTitle("即将前往" + name + ", 是否继续？")
                                    .setPositiveButton(android.R.string.ok, (dialog, which) -> startActivity(intent))
                                    .setNegativeButton(android.R.string.cancel, null)
                                    .show();
                        } else {
                            startActivity(Intent.createChooser(intent, "请选择应用"));
                        }
                    } catch (URISyntaxException e) {
                        e.printStackTrace();

                        view.loadUrl(url);
                    }
                } else {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mProgressBar.setVisibility(View.GONE);
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                mProgressBar.setProgress(newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                setTitle(title);
            }
        });

        String url = getIntent().getStringExtra(INTENT_URL);
        if (url == null) {
            url = NetworkUtil.BASE_URL;
        }

        mWebView.loadUrl(url);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    @Override
    protected void onDestroy() {
        ViewParent parent = mWebView.getParent();
        if (parent != null) {
            ((ViewGroup) parent).removeView(mWebView);
        }

        mWebView.stopLoading();
        // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
        mWebView.getSettings().setJavaScriptEnabled(false);
        mWebView.clearCache(false);
        mWebView.clearHistory();
//        mWebView.clearView();
        mWebView.loadUrl("about:blank");
        mWebView.removeAllViews();
        mWebView.destroy();

        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_html, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_expand:
                showMenu();
                break;
            case android.R.id.home:
                super.onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    private void showMenu() {
        View view = View.inflate(this, R.layout.dialog_menu_html, null);
        final BottomSheetDialog dialog = new BottomSheetDialog(this);
        dialog.setTitle("选择操作");
        dialog.setContentView(view);
        dialog.show();

        view.findViewById(R.id.tv_refresh).setOnClickListener(view16 -> {
            mWebView.reload();
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_copy_link).setOnClickListener(view15 -> {
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            if (cm == null) return;
            ClipData clipData = ClipData.newPlainText(null, mWebView.getUrl());
            cm.setPrimaryClip(clipData);
            showToast("复制网址成功");
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_open_with_browser).setOnClickListener(view14 -> {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(mWebView.getUrl()));
            List<ResolveInfo> infoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            if (infoList == null || infoList.isEmpty()) {
                showToast("没有默认浏览器");
            } else {
                Intent i = Intent.createChooser(intent, "请选择浏览器");
                startActivity(i);
            }
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_share).setOnClickListener(view13 -> {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
            List<ResolveInfo> infoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            if (infoList == null || infoList.isEmpty()) {
                showToast("没有可分享的应用");
            } else {
                Intent i = Intent.createChooser(intent, "分享到");
                startActivity(i);
            }
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_search_current_page).setOnClickListener(view12 -> {
            showToast("暂不支持【当前页搜索】");
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_font_adjust).setOnClickListener(view1 -> {
            showToast("暂不支持【字体调整】");
            dialog.dismiss();
        });
    }
}
